package Math;

import java.util.Arrays;

public class _462_MinimumMovestoEqualArrayElementsII {
    //note: the median of nums is the number that can minimum the steps to make an equal array;
    //if there are two median,calculate them all and select the small one.
    public int minMoves2(int[] nums) {
        if(nums.length<=1) return 0;
        Arrays.sort(nums);
        int lmedian = nums.length / 2 - 1;
        int rmedian = nums.length / 2;
        int lsum = 0,rsum = 0;
        for (int num : nums) {
            lsum += Math.abs(nums[lmedian] - num);
            rsum += Math.abs(nums[rmedian] - num);
        }
        return Math.min(lsum,rsum);
    }
}
